<!--
 * @Author: your name
 * @Date: 2021-08-01 15:05:08
 * @LastEditTime: 2021-08-02 09:47:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \element-study\src\views\Form.vue
-->
<template>
    <!-- ref 用来获取表的实力对象 -->
    <!-- model 当前表单绑定的数据 -->
    <!-- label-width 表示label区域的宽度 -->
    <!-- rules 传入的校验规则 -->
  <div class="formcolor">
      <el-form ref="form" :rules='rules' :model="form" label-width="80px">
          <!-- el-form-item 包裹住每一个表单域 -->
    <el-form-item label="手机号" prop="mobile">
        <!-- v-model 绑定当前表单域的数据，同时实现双向绑定 -->
        <el-input v-model="form.mobile"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
    </el-form-item>
    <el-form-item>
        <el-button type="primary"  @click="login">登录</el-button>
        <el-button @click="resetForm">取消</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>
<script>
export default {
  name: 'Form',
  data () {
    const validPass = (rule, value, callback) => {
      if (value === '123456') {
        callback(new Error('密码过于简单'))
      } else {
        callback()
      }
    }
    return {
      form: {
        mobile: '',
        password: ''
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[345678]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' },
          { validator: validPass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 登录
    login () {
      // 对表单进行兜底校验
      this.$refs.form.validate(valid => {
        if (!valid) return console.log('手机号或密码错误')

        // 通过验证发生请求
      })
    },
    resetForm (formName) {
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style scoped scss>
.formcolor {
    width: 500px;
}
</style>
